// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.linqingying.gitcode.extensions

import com.intellij.openapi.project.Project
import com.intellij.util.AuthData
import com.intellij.util.concurrency.annotations.RequiresEdt
import git4idea.DialogManager
import git4idea.i18n.GitBundle
import git4idea.remote.InteractiveGitHttpAuthDataProvider
import com.linqingying.gitcode.authentication.GCAccountAuthData
import com.linqingying.gitcode.authentication.GCAccountsUtil
import com.linqingying.gitcode.authentication.accounts.GitCodeAccount
import com.linqingying.gitcode.authentication.ui.GitCodeChooseAccountDialog
import com.linqingying.gitcode.i18n.GitCodeBundle
import com.linqingying.gitcode.util.GitCodeUtil.GIT_AUTH_PASSWORD_SUBSTITUTE
import java.awt.Component

internal class GCSelectAccountHttpAuthDataProvider(
  private val project: Project,
  private val potentialAccounts: Map<GitCodeAccount, String?>
) : InteractiveGitHttpAuthDataProvider {

  @RequiresEdt
  override fun getAuthData(parentComponent: Component?): AuthData? {
    val (account, setDefault) = chooseAccount(parentComponent) ?: return null
    val token = potentialAccounts[account]
                ?: GCAccountsUtil.requestNewToken(account, project, parentComponent)
                ?: return null
    if (setDefault) {
      GCAccountsUtil.setDefaultAccount(project, account)
    }

    return GCAccountAuthData(account, GIT_AUTH_PASSWORD_SUBSTITUTE, token)
  }

  private fun chooseAccount(parentComponent: Component?): Pair<GitCodeAccount, Boolean>? {
    val dialog = GitCodeChooseAccountDialog(
      project, parentComponent,
      potentialAccounts.keys, null, false, true,
      GitCodeBundle.message("account.choose.title"), GitBundle.message("login.dialog.button.login")
    )
    DialogManager.show(dialog)

    return if (dialog.isOK) dialog.account to dialog.setDefault else null
  }
}
